import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:zrjz/api/auth_repository.dart';
import 'package:zrjz/comm/http/http_result.dart';
import 'package:zrjz/comm/utils/ext_dart.dart';
import 'package:zrjz/comm/utils/log_utils.dart';
import 'package:zrjz/comm/utils/util.dart';
import 'package:zrjz/comm/widget/dialog/verify_code_dialog/verify_code_dialog.dart';
import 'package:zrjz/comm/widget/dialog/verify_code_dialog/verify_code_dialog_controller.dart';
import 'package:zrjz/modules/auth/login/login_page.dart';
import 'package:zrjz/router/page_router.dart';

import 'forget_psd_state.dart';

class ForgetPsdController extends GetxController {
  final AuthRepository authRepository = Get.find();
  final ForgetPsdState state = ForgetPsdState();

  String? mobilePhoneErrorText; //表单的错误信息展示
  String? codeErrorText;
  String? passwordErrorText;
  String? confirmPasswordErrorText;
  String? phone;
  String? code;
  String? password;
  String? confirmPsd;

  /// 执行手机号码的绑定
  void doBindPhone() {
    mobilePhoneErrorText = null;
    codeErrorText = null;
    passwordErrorText = null;
    confirmPasswordErrorText = null;
    update();

    var phoneController = state.formData['phone']!['controller'];
    var codeController = state.formData['code']!['controller'];
    var passwordController = state.formData['password']!['controller'];
    var confirmPsdController = state.formData['new_password']!['controller'];

    phone = phoneController.text;
    code = codeController.text;
    password = passwordController.text;
    confirmPsd = confirmPsdController.text;

    Log.d('phone:$phone code:$code password:$password confirmPsd:$confirmPsd');

    if (Utils.isEmpty(phone)) {
      mobilePhoneErrorText = "电话号码不能为空";
      update();
    } else if (Utils.isEmpty(code)) {
      codeErrorText = "验证码不能为空";
      update();
    } else if (Utils.isEmpty(password)) {
      passwordErrorText = "密码不能为空";
      update();
    } else if (Utils.isEmpty(confirmPsd)) {
      confirmPasswordErrorText = "确认密码不能为空";
      update();
    } else if (password != confirmPsd) {
      confirmPasswordErrorText = "确认密码不一致，请检查密码";
      update();
    } else {
      _requestForgetPsd();
    }
  }

  /// 请求接口，普通的密码注册
  void _requestForgetPsd() async {
    // //获取到数据
    // SmartDialog.showLoading();
    // var result = await authRepository.forgetPassword(phone, code, password, confirmPsd);
    // SmartDialog.dismiss(status: SmartStatus.loading);
    //
    // //处理数据
    // if (result.isSuccess) {
    //   SmartDialog.showToast(result.msg ?? '密码重置成功');
    //   //成功返回到登录页面
    //   // Get.until((route) => Get.currentRoute == RouterPath.AUTH_LOGIN);
    //    LoginPage.startInstance(LaunchModel.singleTask);
    // } else {
    //   _handleErrorMessage(result);
    // }
  }

  /// 处理网络请求注册的表单错误
  void _handleErrorMessage(HttpResult<dynamic> result) {
    String? errorMessage = result.errorMsg;
    SmartDialog.showToast(errorMessage ?? '未知错误'.tr);

    Map<String, dynamic>? json = result.getErrorJson();
    handleFormError(json, 'password', (str) {
      passwordErrorText = str;
    });
    handleFormError(json, 'phone', (str) {
      mobilePhoneErrorText = str;
    });
    handleFormError(json, 'sms_verification_code', (str) {
      codeErrorText = str;
    });
    handleFormError(json, 'password_confirmation', (str) {
      confirmPasswordErrorText = str;
    });
  }

  /// 默认的App Dialog
  void showVerifyCodedDialog() {
    //隐藏全部的软键盘与焦点
    _phoneFocusNode?.unfocus();
    _codeFocusNode?.unfocus();
    _passwordFocusNode?.unfocus();

    //校验手机号码不能为空
    phone = state.formData['phone']!['controller'].text;
    if (Utils.isEmpty(phone)) {
      mobilePhoneErrorText = "电话号码不能为空";
      update();
    } else {
      SmartDialog.show(
        usePenetrate: false,
        debounce: true,
        clickMaskDismiss: false,
        onDismiss: () {
          //每次取消弹窗都要手动删除弹窗的Controller，不然无法每次弹出都请求接口
          Get.delete<VerifyCodeDialogController>();
        },
        builder: (context) => VerifyCodeDialog(
          confirmAction: (key, code) {
            //发送验证码
            _requestSendSMS(key, code);
          },
        ),
      );
    }
  }

  /// 请求接口，发送验证码
  void _requestSendSMS(String? key, String? code) async {
    // //获取到数据
    // SmartDialog.showLoading();
    // var result = await authRepository.sendPhoneSMS('forget_password', phone, key, code);
    // SmartDialog.dismiss(status: SmartStatus.loading);
    //
    // //处理数据
    // if (result.isSuccess) {
    //   //成功之后开始倒计时
    //   _startCountDown();
    // } else {
    //   String? errorMessage = result.errorMsg;
    //   SmartDialog.showToast(errorMessage ?? '未知错误'.tr);
    // }
  }

  // =========================== 倒计时控制 ===========================

  final int _initialTime = 60; // 初始倒计时时间（秒）
  int countdownTime = 0; // 当前倒计时剩余时间（秒）
  Timer? countdownTimer;
  bool isCounting = false;

  /// 开启倒计时
  void _startCountDown() {
    countdownTime = _initialTime;
    isCounting = true;
    update();

    //每秒的倒计时
    countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countdownTime > 0) {
        countdownTime--;
      } else {
        isCounting = false;
        countdownTimer?.cancel(); // 取消计时器
      }
      update();
    });
  }

  // =========================== 焦点控制 ===========================

  FocusNode? _phoneFocusNode;
  FocusNode? _codeFocusNode;
  FocusNode? _passwordFocusNode;
  FocusNode? _newpasswordFocusNode;

  void _onPhoneFocusChange() {
    if (_phoneFocusNode?.hasFocus == true) {
      mobilePhoneErrorText = null;
      update();
    }
  }

  void _onCodeFocusChange() {
    if (_codeFocusNode?.hasFocus == true) {
      codeErrorText = null;
      update();
    }
  }

  void _onPasswordFocusChange() {
    if (_passwordFocusNode?.hasFocus == true) {
      passwordErrorText = null;
      update();
    }
  }

  void _onNewPasswordFocusChange() {
    if (_newpasswordFocusNode?.hasFocus == true) {
      confirmPasswordErrorText = null;
      update();
    }
  }

  @override
  void onInit() {
    super.onInit();
    _phoneFocusNode = state.formData['phone']!['focusNode'];
    _codeFocusNode = state.formData['code']!['focusNode'];
    _passwordFocusNode = state.formData['password']!['focusNode'];
    _newpasswordFocusNode = state.formData['new_password']!['focusNode'];
  }

  @override
  void onReady() {
    super.onReady();
    _phoneFocusNode?.addListener(_onPhoneFocusChange);
    _codeFocusNode?.addListener(_onCodeFocusChange);
    _passwordFocusNode?.addListener(_onPasswordFocusChange);
    _newpasswordFocusNode?.addListener(_onNewPasswordFocusChange);
  }

  @override
  void onClose() {
    super.onClose();
    _phoneFocusNode?.removeListener(_onPhoneFocusChange);
    _codeFocusNode?.removeListener(_onCodeFocusChange);
    _passwordFocusNode?.removeListener(_onPasswordFocusChange);
    _newpasswordFocusNode?.removeListener(_onNewPasswordFocusChange);
    _phoneFocusNode = null;
    _codeFocusNode = null;
    _passwordFocusNode = null;
    _newpasswordFocusNode = null;

    countdownTimer?.cancel(); // 取消计时器
  }
}
